﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class SelectRole : MonoBehaviour
{
    private GameObject _roleListContent;
    private Button _btnEnter;
    private ToggleGroup _roleListToggleGroup;

    private ModelStudio _modelStudio;
    private TouchEx _modelTouchRotate;//模型旋转节点

    private int _selectRoleIndex = -1;
    private int _lastRoleIndex = 2;
 

    private void Awake()
    {
     
        //角色列表
        _roleListContent = transform.Find("RoleListPanel/roleList/Content").gameObject;
        _roleListToggleGroup = _roleListContent.GetComponent<ToggleGroup>();

        _btnEnter = transform.Find("SelectRoleBtn").GetComponent<Button>();
        _btnEnter.onClick.AddListener(OnCreateBtn);

        _modelTouchRotate = gameObject.Find<TouchEx>("TouchRotate");

        //角色摄影棚

        _modelStudio = new ModelStudio();
        _modelStudio.Init();
       
        _modelTouchRotate.DragCallback += onTouchRotate;

        InitRole();
    }

    private void onTouchRotate(PointerEventData eventData)
    {
        _modelStudio.ModelPlace.transform.Rotate(new Vector3(0,-eventData.delta.x,0));
    }

    private void InitRole()
    {
        //初始化角色数据
        int i = 0;
        foreach (var roleInfo in Server.GetInstance().CurPlayer.AllRole)
        {

            var roleItem = ResManager.GetInstance().load<GameObject>("UI/SelectRole/RoleItem");
            roleItem.transform.SetParent(_roleListContent.transform,false);
            var textName = roleItem.transform.Find("Label").gameObject.GetComponent<Text>();
        
            var toggle = roleItem.GetComponent<Toggle>();
            textName.text = roleInfo.Name;
            toggle.group = _roleListToggleGroup;

            //Toggle添加监听器
            var index = i;
            ++i;
            toggle.onValueChanged.AddListener((isON) =>
            {
                onToggleValueChanged(isON, index);
            });
            toggle.isOn = index == _lastRoleIndex;
        }
    }

    private void onToggleValueChanged(bool isON, int roleIndex)
    {

        if (_selectRoleIndex == roleIndex) { return; }
        _selectRoleIndex = roleIndex;
        //先清除之前留下的模型
        _modelStudio.ClearModel();
        var curRoleInfo = Server.GetInstance().CurPlayer.AllRole[roleIndex];
   
        var modelPath = RoleTable.GetInstance()[curRoleInfo.ModelID].ModelPath;
        var model = ResManager.GetInstance().load<GameObject>(modelPath);
        _modelStudio.SetModel(model);
    }
    private void OnCreateBtn()
    {

        RoleIndexCmd roleIndexCmd = new RoleIndexCmd();
        Debug.Log(_selectRoleIndex);
        roleIndexCmd.Index = _selectRoleIndex;

        Client.GetInstance().SendCmd(roleIndexCmd);
    }

}
